package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.MemberDao;
import com.itheima.dao.TemplateDao;
import com.itheima.entity.PageResult;
import com.itheima.exceptions.BusinessException;
import com.itheima.pojo.CheckGroup;
import com.itheima.pojo.Member;
import com.itheima.pojo.Template;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service(version = "1.0.0",interfaceClass = TemplateService.class)
@Transactional
public class TemplateServiceImpl implements TemplateService {

    @Resource
    private TemplateDao templateDao;

    @Resource
    private MemberDao memberDao;

    @Override
    public PageResult findPage(int currentPage, int pageSize, String queryString) {
        //开启分页查询
        PageHelper.startPage(currentPage,pageSize);
        //调用dao层查询语句
        Page<Template> page = templateDao.findPage(queryString);
        //封装分页查询结果对象
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public List<Template> findAll() {
        return templateDao.findAll();
    }

    @Override
    public void add(Template template) throws BusinessException {
        Integer count = templateDao.findByfileNumber(template);
        if(count>0){
            throw new BusinessException("已存在相同的姓名和档案号，添加失败！");
        }
        //首先添加检查组
        templateDao.add(template);
        //再添加检查组与检查项的关联
        Integer id = template.getId();
        List<Integer> memberIds = template.getMemberIds();
        for (Integer memberId : memberIds) {
            templateDao.setTemplateAndMember(id,memberId);
        }
    }



    @Override
    public void update(Template template) throws BusinessException {
        Integer count = templateDao.findByfileNumber(template);
        if(count>0){
            throw new BusinessException("已存在相同的姓名和档案号，编辑失败！");
        }
        templateDao.update(template);
        //首先删除检查组的旧的关联
        templateDao.deleteMembersByTemplates(template.getId());
        //再添加检查组与检查项的关联
        Integer id = template.getId();
        List<Integer> memberIds = template.getMemberIds();
        for (Integer memberId : memberIds) {

            templateDao.setTemplateAndMember(id,memberId);
        }
    }

    @Override
    public void delete(int id) {
        templateDao.delete(id);
    }

    @Override
    public Member findMember(Long fileNumber) {
         Member member=memberDao.findMemberTemplate(fileNumber);
        System.out.println(member);
        return member;
    }

    @Override
    public Template findById(int id) {
        Template template = templateDao.findById(id);
        template.setMemberIds(templateDao.findMemberIdsByTemplateId(id));
        return template;
    }
}
